package com.liao.mapth;

import android.util.Log;

import java.io.IOException;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

import static android.content.ContentValues.TAG;

/**
 * Created by 27353 on 2017/6/2.
 */

public class Httpquest {

    Httpquest(){
        url="http://";

        this.client =new OkHttpClient();
    }
    private OkHttpClient client;

    public String url;

    public  void setUrl(String Url){
        this.url = Url;
    }

    public String get(String option) throws IOException{
        setUrl(option);
        Request request = new Request.Builder()
                .url(url)
                .build();
        try(Response response = client.newCall(request).execute()){
            return response.body().string();
        }
    }

    public void login(String url, String json)throws Exception{
      /*  RequestBody requestBody = new FormBody.Builder()
                .add("Sno",username)
                .add("PWD",password)
                .build();
        final Request request = new Request.Builder()
                .url(this.url)
                .post(requestBody)
                .build();*/

        RequestBody body = RequestBody.create(JSON, json);
        Request request = new Request.Builder()
                .url(url)
                .post(body)
                .build();
        Call call = client.newCall(request);

        call.enqueue(new Callback() {
            ///错误处理
            @Override
            public void onFailure(Call call, IOException e) {
                e.printStackTrace();
                System.out.println("失败");
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if (response.isSuccessful()){
                    System.out.println("返回成功");
                    Log.i(TAG, "onResponse: "+response.body().string());

                }else {
                    throw  new IOException("服务器错误"+response);
                }

            }
        });
    }
    public static final MediaType JSON
            = MediaType.parse("application/json; charset=utf-8");

    String post(String url, String json) throws IOException {
            RequestBody body = RequestBody.create(JSON, json);
            Request request = new Request.Builder()
                    .url(url)
                    .post(body)
                    .build();
            Response response = client.newCall(request).execute();
             System.out.println("3434");
            return response.body().string();

    }
}
